package com.wontube.smr.bo.download;

import java.io.IOException;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.session.SqlSession;

import com.wontube.smr.bo.pub.Mp3DownloadListenter;
import com.wontube.smr.client.model.po.Mp3Url;
import com.wontube.smr.client.model.po.VideoPage;
import com.wontube.smr.dao.mapper.Mp3UrlMapper;
import com.wontube.smr.dao.mapper.VideoPageMapper;
import com.wontube.smr.pub.DefaultDBHelper;




/**
 * @author yuechao
 * 
 */
public class Mp3DownloadServlet extends HttpServlet {
	private static final long serialVersionUID = -7302439727115917385L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String id = req.getParameter("id");
		if (id == null || "".equals(id)) {
			return;
		}

		VideoPage page;
		Mp3Url mp3Url;

		SqlSession session = DefaultDBHelper.getSqlSession(false);
		try {
			Mp3UrlMapper mapper = session.getMapper(Mp3UrlMapper.class);
			mp3Url = mapper.selectByPrimaryKey(id);
			if (mp3Url == null) {
				return;
			}

			VideoPageMapper pageMapper = session.getMapper(VideoPageMapper.class);
			page = pageMapper.selectByPrimaryKey(mp3Url.getPageId());

			if (page == null) {
				return;
			}
		} finally {
			session.close();
		}

		AsyncContext ac = req.startAsync();
		ac.setTimeout(10 * 60 * 60 * 1000); // 限10小时下载完成
		ac.start(new Mp3DownloadListenter(ac, page, mp3Url));
	}
}
